{include "INC_header.html" title="分组和权限管理/编辑"}
<div id="app-outlet" class="app-outlet">
    <!-- ant-design 应用需要配置 -->
    <a-config-provider :locale="config.locale" :theme="config.theme">
        <div class="app-container">
            <main style="overflow: auto;">
                <div class="ui form padding">
                    <div class="field">
                        <div class="label">分组名称</div>
                        <div class="" style="width: 200px;">
                            <a-input placeholder="名称" maxlength="10" v-model:value="data.name"></a-input>
                        </div>
                    </div>
                    <div class="field">
                        <div class="label">简要说明</div>
                        <div class="" style="width: 500px;">
                            <a-textarea placeholder="简要说明称" maxlength="100" v-model:value="data.desc"></a-textarea>
                        </div>
                    </div>
                    <template v-if="permissionList.length > 0">
                        <a-divider orientation="left" orientation-margin="0px">
                            权限配置
                        </a-divider>
                        <div class="primary-text text-small">
                            <i class="fa fa-info-circle"></i> 父级勾选时，子级均获得授权！
                        </div>
                        <!-- 权限列表 -->
                        <div class="sso-permission-tree" v-for="(module, mi) in permissionList">
                            <a-divider orientation="left" orientation-margin="0px">
                                <a-checkbox v-model:checked="module.checked" @change="switchP(mi)"><i :class="module.icon"></i> {{ module.name }}</a-checkbox>
                            </a-divider>
                            <!-- 权限，暂且最多支持2级授权 -->
                            <div class="sub-tree" v-for="(mp, mpi) in module.sub">
                                <div class="">
                                    <a-checkbox v-model:checked="mp.checked" @change="switchP(mi, mpi)">{{ mp.name }}</a-checkbox>
                                    <a-popover title="权限说明" v-if="mp.tooltip != null && mp.tooltip != undefined">
                                        <template #content>
                                            {{ mp.tooltip }}
                                        </template>
                                        <i class="fa fa-info-circle cursor-pointer"></i>
                                    </a-popover>
                                </div>
                                <div class="sub-tree" v-if="mp.sub != null && mp.sub != undefined && mp.sub.length > 0">
                                    <div class="ant-checkbox-list">
                                    <span v-for="(msp, mspi) in mp.sub" class="margin-right">
                                        <a-checkbox v-model:checked="msp.checked" @change="switchP(mi, mpi, mspi)">{{ msp.name }}</a-checkbox>
                                        <a-popover title="权限说明" v-if="msp.tooltip != null && msp.tooltip != undefined">
                                            <template #content>
                                                {{ msp.tooltip }}
                                            </template>
                                            <i class="fa fa-info-circle cursor-pointer"></i>
                                        </a-popover>
                                    </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </main>
            <footer class="light-background border-top">
                <div class="ui flex-item padding">
                    <div class="center"></div>
                    <div class="end">
                        <a-button href="{url url='/sso/admin/user/group-list'}"><i class="fa fa-arrow-left margin-right-half"></i> 返回</a-button>
                    </div>
                    <div class="end">
                        <a-button type="primary" @click="save()"><i class="fa-regular fa-floppy-disk margin-right-half"></i> 保存设置</a-button>
                    </div>
                </div>
            </footer>
        </div>
    </a-config-provider>
</div>
<script>
    //vue app
    const { createApp } = Vue;
    const { message } = antd;
    const app = createApp({
        data() {
            return {
                config: window.appProviderConfig,
                //数据
                data: {
                    id: parseInt("{$get.id|default:0}"),
                    name: '',
                    desc: '',
                    permission: []
                },
                //可用的权限配置
                permissionList: [],
                //
                saveLoading: false
            }
        },
        mounted() {
            //挂载成功
            this.initData();
        },
        methods: {
            //方法
            initData: function () {
                //获取整个系统用到的权限
                const hide = message.loading("正在加载可用权限信息");
                let self = this;
                axios.get("{url url='/sso/api/admin/permission/list'}").then(({ data }) => {
                    hide();
                    if (data.error === 0) {
                        self.permissionList = data.data;
                        self.getGroup();
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    hide();
                    self.getGroup();
                });
            },
            getGroup: function () {
                if (this.data.id > 0) {
                    const hide = message.loading("正在加载分组信息");
                    let self = this;
                    axios.get("{url url='/sso/api/admin/group'}", {
                        params: {
                            id: this.data.id
                        }
                    }).then(({ data }) => {
                        hide();
                        if (data.error === 0) {
                            self.data = data.data;
                            this.permissionList = self.initPermissionList();
                        } else {
                            message.error(data.message);
                        }
                    }).catch(() => {
                        hide();
                        this.permissionList = self.initPermissionList();
                    });
                } else {
                    this.permissionList = this.initPermissionList();
                }
            },
            //
            initPermissionList: function (list, path, checked) {
                list = list || this.permissionList;
                path = path || "";
                //
                let newList = [];
                //第一层是模块信息
                list.map((item, index) => {
                    item.checked = checked === false || checked === true ? checked : this.matchPermission(item.value, path);
                    if (item.sub) {
                        item.sub = this.initPermissionList(item.sub, [path, item.value].join("/"), checked);
                    }
                    newList.push(item);
                });
                return newList;
            },
            //与现有分组的权限配置进行匹配
            matchPermission: function (value, path) {
                path = path.indexOf("/") === 0 ? path.slice(1) : path;
                let checked = false;
                if (typeof this.data.permission === 'object') {
                    path = path.length > 0 ? [path, value].join("/") : value;
                    let pathList = path.split("/");
                    //遍历获取
                    let p = this.data.permission;
                    let len = pathList.length;
                    for (let i = 0; i < len; i++) {
                        let type = typeof p[pathList[i]];
                        if (type === "object") {
                            p = p[pathList[i]];
                            continue;
                        }
                        let bool = p[pathList[i]] === false || p[pathList[i]] === true ? p[pathList[i]] : undefined;
                        if (bool === undefined) {
                            //结束
                            break;
                        }
                        if (bool === true) {
                            checked = true;
                            break;
                        }
                    }
                }
                return checked;
            },
            switchP: function () {
                let mi = arguments[0], mpi = arguments[1], mspi = arguments[2];
                if (mspi >= 0) {
                    let checkAllLast = true;
                    this.permissionList[mi].sub[mpi].sub.map(item => {
                        if (!item.checked) {
                            checkAllLast = false;
                        }
                    });
                    this.permissionList[mi].sub[mpi].checked = checkAllLast;
                    //验证
                    let checkAll = true;
                    this.permissionList[mi].sub.map(item => {
                        if (!item.checked) {
                            checkAll = false;
                        }
                    });
                    this.permissionList[mi].checked = checkAll;
                } else if (mpi >= 0) {
                    let checked = this.permissionList[mi].sub[mpi].checked;
                    if (this.permissionList[mi].sub[mpi].sub) {
                        this.permissionList[mi].sub[mpi].sub = this.initPermissionList(this.permissionList[mi].sub[mpi].sub, null, checked);
                    }
                    //验证
                    let checkAll = true;
                    this.permissionList[mi].sub.map(item => {
                        if (!item.checked) {
                            checkAll = false;
                        }
                    });
                    this.permissionList[mi].checked = checkAll;
                } else {
                    let checked = this.permissionList[mi].checked;
                    this.permissionList[mi].sub = this.initPermissionList(this.permissionList[mi].sub, null, checked);
                }
            },
            getPermissionChecked: function (list) {
                list = list || this.permissionList;
                let result = {};
                list.map(item => {
                    if (item.checked) {
                        result[item.value] = true;
                    } else {
                        //如果有下级
                        if (typeof  item.sub === "object") {
                            result[item.value] = this.getPermissionChecked(item.sub);
                        } else {
                            result[item.value] = false;
                        }
                    }
                });
                return result;
            },
            //保存配置
            save: function () {
                if (this.saveLoading) {
                    return;
                }
                if (this.data.name.toString().length < 2) {
                    return message.error("分组名称至少2个字符");
                }
                //处理权限
                let permission = this.getPermissionChecked();
                this.saveLoading = true;
                let self = this;
                const hide = message.loading("正在保存");
                axios.post("{url url='/sso/api/admin/group/save'}", {
                    id: this.data.id,
                    name: this.data.name,
                    desc: this.data.desc,
                    permission: JSON.stringify(permission)
                }).then(({ data }) => {
                    self.saveLoading = false;
                    if (data.error === 0) {
                        message.success("保存成功");
                        window.location.href = "{url url='/sso/admin/user/group-list'}";
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    hide();
                    self.saveLoading = false;
                    message.error("服务端繁忙");
                });
            }
        }
    }).use(antd);
    //挂载
    const vm = app.mount("#app-outlet");
    //
    if (window.parent.length > 0) {
        window.parent.postMessage({
            event: "location",
            data: [
                { name:"分组/权限" },
                { name:"编辑" }
            ]
        });
    }
</script>
{include "INC_footer.html"}